<?php
/**
 * 鉴权中间件
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\api\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class ApiAuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $url = $request->request_url;

        $url_lower    = strtolower($url);
        $except_lower = array_map('strtolower', array_merge(API_LOGIN_EXCEPT, API_AUTH_EXCEPT));
        $need_check   = !in_array($url_lower, $except_lower, false);

        // 需要验证登录 && 没有用户信息
        if ($need_check && !isset($request->user)) {
            return api_unauthorized('未登录');
        }

        return $handler($request);
    }
}
